<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class TagsController extends Controller
{
	
	// 标签库
	public function index( Request $request )
	{
        // 开始
        // 获取路由
        $route_array = request()->route()->getAction();
        $controller = explode("\\",$route_array['controller']);
        $result = explode("@",$controller[3]);
        // 控制器 	$result[0];
        // 方法 	$result[1];
        $auth_final = '';
        foreach( Session::get('auths') as $key=> $auth_info )
        {
            // 符合条件
            if( $auth_info['controller']==$result[0] && $auth_info['func']==$result[1] )
            {
                $auth_final = true;
                break;
            }else
            {
                $auth_final = false;
            }
        }
        // 权限验证失败
        if( !$auth_final )
        {
            return redirect('/')->with( ['authinfo'=>'没有此项权限'] );
        }
        // 结尾
		// 获取搜索内容
		$keyword = $request -> input('keyword',"");
		if( empty($keyword) )
		{
			// 为空 说明没有搜索
			$one = 'id';
			$two = '!=';
			$three = '0';
		}else{
			$one = 'name';
			$two = 'like';
			$three = '%'.$keyword.'%';
			
		}
		
		// 获取所有标签
		$tags = DB::table('tag')
				-> where( $one,$two,$three )
				-> paginate(10);
		return view('tags.index',['tags'=>$tags,'request'=>$keyword]);
	}
	
	
	// 删除标签
	public function delTags( Request $request )
	{
		// 包含 评论id
		$data = $request -> except('_token');
		
		// 清除无效值
		unset($data['all'][0]);	
		
		foreach( $data['all'] as $key => $tag_id )
		{
			$history = DB::table('tag_record as tr')
				-> select('t.name','t.id')
				-> leftJoin('tag as t','t.id','=','tr.tag_id')
				-> where('tr.tag_id',$tag_id)
				-> first();
			if( !empty($history) )
			{
				$this -> show_msg( $history->name.' 下有资讯,无法删除');
			}
		}
		// 1.主表
		$res = DB::table('tag')
				-> whereIn( 'id',$data['all'] )
				-> delete();
		if( $res )
		{
			$this -> show_msg('删除成功');
		}
		$this -> show_msg('删除失败');
	
	}
	
	
}
